package com.leyou.user.controller;

import com.leyou.common.exception.pojo.LyException;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 校验用户名或者手机号
     */
    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkNameOrPhone(@PathVariable("data") String data,
                                                    @PathVariable("type") Integer type){
        Boolean isUsable = userService.checkNameOrPhone(data, type);
        return ResponseEntity.ok(isUsable);
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendCheckCode(@RequestParam("phone") String phone){
        userService.sendCheckCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     * 注册
     * @Valid 注解放到某个对象前，表示可以对此对象中的属性使用hibernate的方式进行数据校验
     * BindingResult result参数必须紧跟在被校验的数据之后，收集校验结果
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        if(result.hasErrors()){
            String errorMsg = result.getFieldErrors()
                    .stream()
                    .map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            //枚举是提前将所有可能性列出来，但是此处的异常，并不确定。
            throw new LyException(400, errorMsg);
        }
        userService.register(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("/query")
    public ResponseEntity<User> findUserInfo(@RequestParam("username") String username,
                                             @RequestParam("password") String password){
        User user = userService.findUserInfo(username, password);
        return ResponseEntity.ok(user);
    }


}
